#include "class-engine.h"

/***
 * cEngine Member Functions
 **/

cEngine::cEngine(){

	if (!initSession()){
        printf("", SDL_GetError());
		exit(1);
	}	
}

// Destructor
cEngine::~cEngine(){

	// End the SDL Instance
    SDL_Quit();
}

bool cEngine::initSession(){

	// Initialise the SDL subsystems
    if ( SDL_Init(SDL_INIT_EVERYTHING) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return false;
    }

	// Set the program window caption
	SDL_WM_SetCaption( "Encounter Engine (2011 edition)", NULL );

	// Turn off the SDL Cursor
	//SDL_ShowCursor(0);

	// Set some OpenGL Attributes
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);		// Sets double buffer
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);	// forces acceleration
	
	// Create the screen instance
    if (SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH, SDL_OPENGL) == NULL) {
		printf("Unable to set video mode: %s\n", SDL_GetError());
		return false;
	}
	
	// Some OpenGL prep work
	glClearColor(0, 0, 0, 0);	// Set the clear colour to black	
	glEnable(GL_TEXTURE_2D);	// Enable Texture Mapping
	
	// Enable Alpha Blending
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	glColor4f(1.0f,1.0f,1.0f,1.0f);
	glEnable(GL_ALPHA_TEST);

    glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); // Set the viewport

    glMatrixMode(GL_PROJECTION);	// Switch to GL_PROJECTION
    glLoadIdentity();

    glOrtho(0, GAME_WIDTH, GAME_HEIGHT, 0, -1, 1);	// OpenGL's 2D mode :D 
    
    glMatrixMode(GL_MODELVIEW);	// Switch to GL_MODELVIEW
    glLoadIdentity();

	// Were there any problems in the above?
    if(glGetError() == GL_NO_ERROR) 
	{ 
		return true; 
	}else{ 
		return false;
	}
}

void cEngine::getEvent(){
	
	// Poll the event handler
	SDL_PollEvent(&event);

	// Lets you quit with the red X in the top-right corner
	if (event.type == SDL_QUIT){  
		exit(0);  
	}
}

void cEngine::cls(){

	// Clear the screen
	glClear(GL_COLOR_BUFFER_BIT);

}

void cEngine::refresh(){
	
	glFlush();
	glFinish();

	// Draw the buffered contents
	SDL_GL_SwapBuffers(); 
}